﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using HandyControl.Controls;
using MyHelper;
using clf.weighing.entity;
using Button = System.Windows.Controls.Button;
using Brushes = System.Windows.Media.Brushes;
using Color = System.Windows.Media.Color;
using HandyControl.Data;

namespace weighing
{
    /// <summary>
    /// CompanyWindow.xaml 的交互逻辑
    /// </summary>
    public partial class CompanyWindow : GlowWindow
    {
        #region variables
        public List<CompanyVo>? mCompanyVos;
        private bool isEdit = false;
        private bool isEditing = false;
        private CompanyVo mEditCompanyVo = new CompanyVo(new Company());
        private bool isLoading = false;
        #endregion
        public CompanyWindow()
        {
            InitializeComponent();

            CommonFunction.ShowCustomIcon(this);
        }
        #region window event

        private void Company_Window_Loaded(object sender, RoutedEventArgs e)
        {

        }

        private void Company_Window_ContentRendered(object sender, EventArgs e)
        {
            LoadData();
        }

        private void Company_Window_KeyUp(object sender, System.Windows.Input.KeyEventArgs e)
        {
            if (e.Key == Key.Escape) this.Close();
        }
        #endregion


        //private void LoadData() {
        //    this.Data_Grid.ItemsSource = null;
        //    var list  = CompanyDao.Instance.GetList();
        //    mCompanyVos = list?.Select((i) => { return new CompanyVo(i); }).ToList();
        //    this.Data_Grid.ItemsSource = mCompanyVos;
        //}

        #region Page 

        /// <summary>
        /// 页码改变
        /// </summary>
        private void Pagination_PageUpdated(object sender, FunctionEventArgs<int> e)
        {
            // this.pageUI.PageIndex = e.Info;
            LoadData();
        }


        private void PageSiaeBox_LostFocus(object sender, RoutedEventArgs e)
        {
            int size = 0;
            string s = this.PageSizeBox.Text;
            try
            {
                size = Convert.ToInt32(s);
            }
            catch (Exception ex)
            {
            }
            if (size == 0)
            {
                this.PageSizeBox.SelectedIndex = 1;
            }
            else
            {
                LoadData();
            }
        }

        private void PageSiaeBox_Selected(object sender, RoutedEventArgs e)
        {
            LoadData();
        }
        private int GetPageCount()
        {
            string key = this.searcher.Text;
            var count = CompanyDao.Instance.CountAll(key);
            return count;
        }
        #endregion

        private void LoadData()
        {
            if (this.IsLoaded == false) return;       
            if (isLoading == true) return;
            isLoading = true;
            int count = GetPageCount();

            int size = 20;
            if (this.PageSizeBox.SelectedIndex >= 0)
            {
                var item = this.PageSizeBox.SelectedValue as ComboBoxItem;
                size = Convert.ToInt32(item?.Content?.ToString() ?? "20");
            }
            else
            {
                size = Convert.ToInt32(this.PageSizeBox.Text);
            }
            if (count == 0)
            {
                if (this.pageUI != null) this.pageUI.MaxPageCount = 0;
                this.Data_Grid.ItemsSource = null;
                isLoading = false;
                return;
            }
            else
            {
                int pc = count <= size ? 1 : ((count / size) + (count % size > 0 ? 1 : 0));
                if (this.pageUI != null) this.pageUI.MaxPageCount = pc;
            }
            int pageindex =  (this.pageUI != null) ? this.pageUI.PageIndex : 0;
            if (pageindex <= 0) pageindex = 1;
            string key = this.searcher.Text;
            this.Data_Grid.ItemsSource = null;
            var list = CompanyDao.Instance.SelectPage(pageindex, size, key);
            mCompanyVos = list?.Select((i) => { return new CompanyVo(i); }).ToList();
            this.Data_Grid.ItemsSource = mCompanyVos;
            isLoading = false;
        }

        /// <summary>
        /// 新增公司
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void AddCompanyBtn_Click(object sender, RoutedEventArgs e)
        {
            if (isEditing)
            {
                return;
            }
            isEdit = false;
            this.DrawerHeaderTB.Text = "新增";
            this.FirstPinYinTb.Visibility = Visibility.Collapsed;
            this.AddDrawerRight.IsOpen = true;
        }

        private void EditBtn_Click(object sender, RoutedEventArgs e)
        {
            isEdit = true;
            isEditing = true;
            this.DrawerHeaderTB.Text = "修改";
            this.FirstPinYinTb.Visibility = Visibility.Visible;
            var button = sender as Button;
            var vo = button?.Tag as CompanyVo;
            BindEditValue(vo?.mCompany);
            mEditCompanyVo = vo;
            this.AddDrawerRight.IsOpen = true;
        }

        private void DelBtn_Click(object sender, RoutedEventArgs e)
        {
            Button button = sender as Button;
            var companyvo = button.Tag as CompanyVo;

            if (companyvo.Id == App.CurrentCompanyVo.Id) {
                string msg = "禁止操作";
                CommonFunction.AlertInfo(msg,this);
                return;
            }
            var m = "是否要删除 公司：" + companyvo.FullName;
            var reault = CommonFunction.Ask(m);

            if (reault == MessageBoxResult.Yes)
            {
               
                var res = CompanyDao.Instance.Delete(companyvo.mCompany);

                if (res == 1)
                {
                    this.mCompanyVos.Remove(companyvo);
                    this.Data_Grid.ItemsSource = null;
                    this.Data_Grid.ItemsSource = this.mCompanyVos;
                   CommonFunction.AlertInfo("操作成功");
                }
                else if (res == -1)
                {
                    CommonFunction.AlertInfo("操作失败：该公司已经产生了过磅数据，不能删除！");
                }
                else
                {
                    CommonFunction.AlertInfo("操作失败");
                    Growl.ErrorGlobal("操作失败");
                }
            }
        }

        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void saveBtn_Click(object sender, RoutedEventArgs e)
        {
            if (isEdit) {
                Eidt();
            }
            else
            {
                Insert();
            }
        }

        private void Insert() {
            Company company = new Company();

            company.fullName = this.nameTb.Text.Trim();
            if (company.fullName.IsNullOrEmpty() || !company.fullName.Length.IsBetween(2, 50))
            {
                this.saveBtn.IsChecked = false;
                CommonFunction.AlertInfo("公司全称的长度为2到50 个字之间");
                return;
            }
            company.nameFirstCase = StringHelper.GetFirstPinyin(company.fullName);

            company.shortName = this.shortNameTb.Text.Trim();
            if (company.shortName.IsNullOrEmpty() || !company.shortName.Length.IsBetween(2, 20))
            {
                this.saveBtn.IsChecked = false;
                CommonFunction.AlertInfo("公司简称的长度为2到20 个字之间");
                return;
            }

            company.connectPeople = this.connectPeopleTb.Text.Trim();
            //if (company.ConnectPeople.IsNullOrEmpty() || !company.ConnectPeople.Length.IsBetween(2, 5))
            //{
            //    this.saveBtn.IsChecked = false;
            //    MMessageBox.GetInstance(this).ShowErrorAlert("联系人姓名长度为2到5 个字之间");
            //    return;
            //}
            company.connectPhone = this.phoneTb.Text.Trim();
            //if (!RegexHelper.IsMobilePhoneNumber(company.ConnectPhone))
            //{
            //    this.saveBtn.IsChecked = false;
            //    MMessageBox.GetInstance(this).ShowErrorAlert("联系人联系电码不正确");
            //    return;
            //}

            if (CompanyDao.Instance.IsExist(company.fullName))
            {
                this.saveBtn.IsChecked = false;
                CommonFunction.AlertInfo("公司名称已经存在！");
                return;
            }

            company.legalPerson = this.legalPersonTb.Text.Trim();
            company.id = Snowflake.Instance().GetId();
            company.isCoalSource = 0;
            company.addUserId = App.CurrentUser.id;
            company.addUserName = App.CurrentUser.name;
            company.updateTime = DateTime.Now;
            company.addTime = company.updateTime;
            company.updateUserId = company.addUserId;
            company.updateUserName = company.addUserName;
            company.isDelete = 0;
            var res = CompanyDao.Instance.Sqlite.Insert(company);

            if (res > 0)
            {
                this.saveBtn.IsChecked = false;
                Growl.SuccessGlobal("保存成功！");
                this.mCompanyVos.Insert(0, new CompanyVo(company));
                this.Data_Grid.ItemsSource = null;
                this.Data_Grid.ItemsSource = mCompanyVos;                
                ResertInput();
            }
            else
            {
                this.saveBtn.IsChecked = false;
                string msg = "保存数据失败！";
                CommonFunction.AlertInfo(msg);             
            }
        }

        private void Eidt()
        {
            if (mEditCompanyVo == null) {
                ResertInput();
                return;
            }

            mEditCompanyVo.LegalPerson = legalPersonTb.Text.Trim();
            String people = this.connectPeopleTb.Text.Trim();

            mEditCompanyVo.ConnectPeople = people;

            String phone = this.phoneTb.Text.Trim();
            if (!string.IsNullOrEmpty(phone))
            {
                if (!RegexHelper.IsMobilePhoneNumber(phone))
                {
                    this.saveBtn.IsChecked = false;
                    CommonFunction.AlertInfo("联系人联系电码不正确");
                    return;
                }
            }           
            mEditCompanyVo.ConnectPhone = phone;
            mEditCompanyVo.UpdateUserId = App.CurrentUser.id;
            mEditCompanyVo.UpdateUserName = App.CurrentUser.name;
            mEditCompanyVo.UpdateTime = DateTime.Now;
            mEditCompanyVo.FullName = this.nameTb.Text.Trim();
            mEditCompanyVo.ShortName = this.shortNameTb.Text.Trim();
            string py = this.FirstPinYinTb.Text.Trim();
            if (py.IsNullOrEmpty())
            {
                mEditCompanyVo.NameFirstCase = StringHelper.GetFirstPinyin(mEditCompanyVo.FullName);
            }
            else
            {
                mEditCompanyVo.NameFirstCase = py;
            }

            var res = CompanyDao.Instance.Sqlite.Update(mEditCompanyVo.mCompany);
            if (res > 0)
            {
                this.saveBtn.IsChecked = false;
                Growl.SuccessGlobal("保存成功！");
                LoadData();
                ResertInput();
            }
            else
            {
                this.saveBtn.IsChecked = false;
                string msg = "保存数据失败！";
                CommonFunction.AlertInfo(msg);
            }

        }
        private void CancelBtn_Click(object sender, RoutedEventArgs e)
        {
            isEditing = false;
            this.AddDrawerRight.IsOpen = false;
        }
        /// <summary>
        /// 修改时设置值 
        /// </summary>
        private void BindEditValue(Company? company) {
            if (company != null)
            {
                this.nameTb.Text =company.fullName;
                //this.nameTb.IsReadOnly = true;
                this.shortNameTb.Text = company.shortName;
                this.FirstPinYinTb.Text = company.nameFirstCase;
                this.legalPersonTb.Text =company.legalPerson;
                this.phoneTb.Text = company.connectPhone;
                this.connectPeopleTb.Text = company.connectPeople;
            }

        }

        public void ResertInput() {
            mEditCompanyVo = null;
            //this.nameTb.IsReadOnly = false;
            //this.shortNameTb.IsReadOnly = false;
            this.nameTb.Text = "";
            this.FirstPinYinTb.Text = "";
            this.shortNameTb.Text = "";
            this.legalPersonTb.Text = "";
            this.phoneTb.Text = "";
            this.connectPeopleTb.Text = "";
            this.AddDrawerRight.IsOpen = false;
        }

        private void RefreshBtn_Click(object sender, RoutedEventArgs e)
        {
            this.searcher.Text = string.Empty;
            this.pageUI.PageIndex = 1;
            this.PageSizeBox.SelectedIndex = 1;
            LoadData();
        }

 
        #region filter

        /// <summary>
        /// 过虑
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SearchBar_OnSearchStarted(object sender, HandyControl.Data.FunctionEventArgs<string> e)
        {
          LoadData();
        }

        private void Searcher_TextChanged(object sender, TextChangedEventArgs e)
        {
            var text = this.searcher.Text;
            if (string.IsNullOrEmpty(text) || text.Length < 2)
            {
                this.Data_Grid.ItemsSource = null;
                this.Data_Grid.ItemsSource = mCompanyVos;
            }
            else
            {
                FilterByKey();
            }
        }

        private void FilterByKey()
        {
            string key = this.searcher.Text.Trim();
            var temp = new List<CompanyVo>();
            if (!string.IsNullOrEmpty(key))
            {
                mCompanyVos?.ForEach((item) =>
                {
                    if (item.NameFirstCase.Contains(key.ToUpper()) || item.NameFirstCase.Contains(key) || item.FullName.Contains(key) || item.ShortName.Contains(key))
                    {
                        temp.Add(item);
                    }
                });
                if (temp.Count > 0)
                {
                    this.Data_Grid.ItemsSource = temp;
                }
                else
                {
                    Growl.Info("当前页，没有过虑到任何数据，请换个关键字，或点击右侧的搜索图标", "main");
                    this.Data_Grid.ItemsSource = null;
                }
            }
            else
            {
                this.Data_Grid.ItemsSource = null;
                this.Data_Grid.ItemsSource = mCompanyVos;
            }

        }
        #endregion


        #region DataGrid
        private void DataGrid_LoadingRow(object sender, DataGridRowEventArgs e)
        {
            e.Row.Header = e.Row.GetIndex() + 1;

            if (e.Row.DataContext is WeighingBillVo bill)
            {
                if (bill.Status == 0)
                {
                    e.Row.Foreground = Brushes.Red;
                }
                else
                {
                    e.Row.Foreground = new SolidColorBrush(Color.FromRgb(66, 66, 66));
                }
                if (bill.UpGovernmentStatus == 1)
                {
                    e.Row.Foreground = Brushes.LightGreen;
                }
                else if (bill.UpGovernmentStatus == 2)
                {
                    e.Row.Foreground = Brushes.Green;
                }
            }

        }

        private void DataGrid_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
         
        }

        #endregion


        #region 导入 下载导入模板 导出
        /// <summary>
        /// 是否正在导入
        /// </summary>
        private bool isImporting = false;

        /// <summary>
        /// 导入
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ImportBtn_Click(object sender, RoutedEventArgs e)
        {
            if (isImporting == false)
            {
                isImporting = true;
                string fileName = "";
                //弹出保存对话框,并保存文件
                var ofd = new Microsoft.Win32.OpenFileDialog
                {
                    DefaultExt = ".xlsx",
                    Filter = "EXCL Files (*.xlsx,*.xls)|*.xlsx|JSON Files (*.json)|*.json|All files (*.*)|*.*"

                };
                if (ofd.ShowDialog() == true)
                {
                    if (ofd.FileName != "")
                    {
                        fileName = ofd.FileName;  //将其进行保存到指定的路径                                                   
                    }
                }
                if (!FileHelper.Exists(fileName))
                {
                    Growl.Clear();
                    Growl.Error("未选择需要导入的文件");
                    isImporting = false;
                    return;
                }

                if (!(fileName.EndsWith(".xlsx")
                    || fileName.EndsWith(".xls")
                    || fileName.EndsWith(".json")))
                {
                    Growl.Clear();
                    Growl.Error("导入的文件只能是*.xlsx、*.xls、*.json");
                    isImporting = false;
                    return;
                }

                if (fileName.EndsWith(".json"))
                {
                    ImportFromJson(fileName);
                }
                else
                {
                    ImportFromExcl(fileName);
                }

                isImporting = false;
            }
        }

        private void ImportFromExcl(string fileName)
        {
            var headers = GetHeaderDic();
            var res = ExclHelper.Import(1, headers, fileName);
            Growl.Clear();
            if (res.Count > 0)
            {
                Growl.Success($"成功读取 {res.Count} 条数据，进行异步保存，请留意桌面的导入日志");
                Growl.Success(TimeInfo(res.Count));
                var task = SaveImportDataAsync(res);
                Console.WriteLine("先输出");
                task.ContinueWith((t) =>
                {
                    if (t.IsCompleted)
                    {
                        Growl.Success("导入结束");
                        this.Dispatcher.Invoke(() => { LoadData(); });
                    }
                    else if (t.IsFaulted)
                    {
                        Growl.Clear();
                        Growl.Info("导入结束,有错：" + t.Exception?.InnerException?.Message ?? "");
                    }
                    else { }
                });
            }
            else
            {
                Growl.Info("导入 0 条数据");
            }
        }


        private void ImportFromJson(string fileName)
        {
            string json = FileHelper.Reader(fileName, Encoding.UTF8);
            if (!CommonFunction.IsJsonContent(json))
            {
                Growl.Clear();
                Growl.Info("文件内容为空或不符合");
                return;
            }
            Growl.Clear();

            List<Company> datas = JsonHelper.JsonToObject<List<Company>>(json);

            if (datas == null || datas.Count == 0)
            {
                Growl.Info("导入 0 条数据");
                return;
            }

            if (datas.Count > 0)
            {
                Growl.Success($"成功读取 {datas.Count} 条数据，进行异步保存，请留意桌面的导入日志");
                Growl.Success(TimeInfo(datas.Count));
                var task = SaveImportDataJsonAsync(datas);

                task.ContinueWith((t) =>
                {
                    if (t.IsCompleted)
                    {
                        Growl.Success("导入结束");
                        this.Dispatcher.Invoke(() => { LoadData(); });
                    }
                    else if (t.IsFaulted)
                    {
                        Growl.Clear();
                        Growl.Info("导入结束,有错：" + t.Exception?.InnerException?.Message ?? "");
                    }
                    else { }
                });
            }
            else
            {
                Growl.Info("导入 0 条数据");
            }
        }

        /// <summary>
        /// 时间提示
        /// </summary>
        /// <param name="counts"></param>
        /// <returns></returns>
        private string TimeInfo(long counts)
        {
            string res = "每秒大概10条，大概需要 ";
            string u = "秒钟";
            long t = counts / 10;
            if (counts > 1000)
            {
                u = "分钟";
                t = counts / 10 / 60;
            }
            return res + t + u;
        }


        private async Task<bool> SaveImportDataJsonAsync(List<Company> datas)
        {
            return await Task<bool>.Run(() =>
            {
                int succCount = 0;
                int failCount = 0;
                string title = "公司信息JSON导入";
                string time = DateTimeHelper.getCurrentDateTime();
                var msg = "=================================================================\r\n ";
                msg += $"{time} {title}，有 {datas.Count} 条数据要处理\r\n";
                Console.WriteLine(msg);
                for (int i = 0; i < datas.Count; i++)
                {
                    var com = datas[i];
                    try
                    {
                        var temp = CompanyDao.Instance.FindByFullName(com.fullName);
                        //存在，不导入
                        if (temp != null)
                        {
                            msg += $"\r\n {i + 1} \t {com.fullName} 导入失败 已经存在";
                            failCount++;
                            continue;
                        }

                        var idc = CompanyDao.Instance.FindById(com.id);
                        if (idc != null)
                        {
                            if (temp == null)
                            {
                                com.id = IdHelper.LongID;
                            }
                            else
                            {
                                msg += $"\r\n {i + 1} \t {com.fullName} 导入失败 已经存在";
                                failCount++;
                                continue;
                            }
                        }

                        // save data to databases;
                        if (com.isDelete == null) { com.isDelete = 0; }
                        int res = CarDao.Instance.Sqlite.Insert(com);
                        if (res > 0)
                        {
                            succCount++;
                            msg += $"\r\n {i + 1} \t {com.fullName} 导入成功";
                        }
                        else
                        {
                            msg += $"\r\n {i + 1} \t {com.fullName} 导入失败";
                            failCount++;
                        }
                    }
                    catch (Exception ex)
                    {

                        msg += $"\r\n导入{com.fullName} 出错:{ex.Message} --- \r\n";
                    }
                }

                msg += $" \r\n{time} 处理完成,成功 {succCount} 失败：{failCount} 。\r\n ";
                msg += "=================================================================\r\n";
                Console.WriteLine("处理完成");
                string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
                var d = DateTimeHelper.getCurrentDateTime(DateTimeHelper.DateFormat);
                string file = System.IO.Path.Combine(desktopPath, d + $"_{title}日志.txt");
                FileHelper.WriteAppend(file, msg);
                return true;
            });

        }

        private async Task<bool> SaveImportDataAsync(List<String> result)
        {
          return  await Task<bool>.Run(() =>
            {
                int succCount = 0;
                int failCount = 0;
                string title = "公司信息导入";
                string time = DateTimeHelper.getCurrentDateTime();
                var msg = "=================================================================\r\n ";
                msg += $"{time} {title}，有 {result.Count} 条数据要处理\r\n";
                Console.WriteLine(msg);
                var companys = new List<Company>();
                for (int i = 0; i < result.Count; i++)
                {
                    string json = result[i];
                    var dic = JsonHelper.JsonToObject<Dictionary<string, string>>(json);
                    var nDic = new Dictionary<string, string>();

                    foreach (var item in dic)
                    {
                        string key = StringHelper.LowerCaseFirstLetter(item.Key);
                        var sub = "Text";//后辍
                        if (key.EndsWith(sub))
                        {
                            string value = item.Value == "是" ? "1" : "0";
                            nDic.Add(key.Substring(0, key.Length - sub.Length), value);
                        }
                        else
                        {
                            if (nDic.ContainsKey(key))
                            {
                                nDic[key] = item.Value;
                            }
                            else
                            {
                                nDic.Add(key, item.Value);
                            }
                        }
                    }
                    var companyJson = JsonHelper.ObjectToJson(nDic);
                    Console.WriteLine("new company Json:" + companyJson);

                    var company = JsonHelper.JsonToObject<Company>(companyJson);
                    if (company == null)
                    {
                        msg += $" \r\n {companyJson} \t 表格数据不能被转化成有效的公司信息数据";
                    }
                    else
                    {
                        company.isDelete = 0;
                        company.id = IdHelper.LongID;
                        company.addUserId = 0;
                        company.nameFirstCase = StringHelper.GetFirstPinyin(company.fullName);
                        if (string.IsNullOrEmpty(company.addUserName)) company.addUserName = "";
                        company.connectPhone = company.connectPhone.Replace(" ", "");
                        if (company.addTime == null) company.addTime = DateTime.Now;
                        companys.Add(company);
                    }
                }

                //开始处理数据
                for (int i = 0; i < companys.Count; i++)
                {
                    var company = companys[i];
                    if (company.fullName.IsNullOrEmpty())
                    {
                        msg += $"\r\n {i + 1} \t 未填写正确公司名称";
                        failCount++;
                        continue;
                    }
                    //判断是否存在 
                    if (CompanyDao.Instance.IsExist(company.fullName))
                    {
                        msg += $"\r\n {i + 1} \t {company.fullName} 导入失败 已经存在";
                        failCount++;
                        continue;
                    }
                    company.id += i;
                    // save data to databases;
                    int res = CompanyDao.Instance.Sqlite.Insert(company);
                    if (res > 0)
                    {
                        succCount++;
                        msg += $"\r\n {i + 1} \t {company.fullName} 导入成功";
                    }
                    else
                    {
                        msg += $"\r\n {i + 1} \t {company.fullName} 导入失败";
                        failCount++;
                    }
                }
                msg += $" \r\n{time} 处理完成,成功 {succCount} 失败：{failCount} 。\r\n ";
                msg += "=================================================================\r\n";
                Console.WriteLine("处理完成");
                string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
                var d = DateTimeHelper.getCurrentDateTime(DateTimeHelper.DateFormat);
                string file = System.IO.Path.Combine(desktopPath, d + $"_{title}日志.txt");
                FileHelper.WriteAppend(file, msg);
                return true;
            });

        }

        /// <summary>
        /// 下载导入模板
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TemplateBtn_Click(object sender, RoutedEventArgs e)
        {
            if (isExporting == false)
            {
                isExporting = true;
                string title = "公司信息导入模板";
                string filename = title;
                string subtitle = "导入模板";
                Dictionary<string, string> headers = GetHeaderDic();

                var res = ExclHelper.DownTemplate(headers, filename, title, subtitle);

                Growl.Clear();
                if (res)
                {
                    Growl.Success("下载成功");
                }
                else
                {
                    Growl.Error("模板下载失败");
                }
                isExporting = false;
            }
        }

        private Dictionary<string, string> GetHeaderDic()
        {
            var headerDic = new Dictionary<string, string>();
            foreach (var column in this.Data_Grid.Columns)
            {
                if (column is DataGridTextColumn textColumn)
                {
                    var binding = textColumn.Binding as System.Windows.Data.Binding;
                    var key = binding?.Path.Path ?? "";
                    var val = textColumn.Header.ToString();
                    headerDic.Add(key, val ?? "");
                }
            }
            return headerDic;
        }

        #region expor excl
        private bool isExporting = false;
        private void ExportBtn_Click(object sender, RoutedEventArgs e)
        {
            if (isExporting == false)
            {
                isExporting = true;
                string title = "客户公司信息";
                string filename = DateTimeHelper.getCurrentDateTime(DateTimeHelper.DateFormat) + title;
                string subtitle = "导出的公司明细信息";
                var result = ExclHelper.ExclExprotToExcelWitchStatisticInfo(this.Data_Grid, filename, title, subtitle, "导出时间:" + DateTimeHelper.getCurrentDateTime(), "", null);
                Growl.Clear();
                if (result > 0)
                {
                    Growl.Success($"导出成功");
                }
                else
                {
                    Growl.Info("导出失败");
                }
                isExporting = false;
            }
        }
        #endregion

        #endregion

    }
}
